package com.tjmc.nsia.core.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tjmc.nsia.core.dao.entity.NsiaMenu;
import com.tjmc.nsia.core.dao.entity.NsiaUser;
import com.tjmc.nsia.core.dao.entity.NsiaUserMenu;
import com.tjmc.nsia.core.dao.mapper.NsiaMenuMapper;
import com.tjmc.nsia.core.dao.mapper.NsiaUserMapper;
import com.tjmc.nsia.core.dao.mapper.NsiaUserMenuMapper;
import com.tjmc.nsia.core.service.NsiaMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2024/07/04
 */
@Service
public class NsiaMenuServiceImpl extends ServiceImpl<NsiaMenuMapper, NsiaMenu> implements NsiaMenuService {

    @Autowired
    private NsiaUserMenuMapper nsiaUserMenuMapper;

    @Autowired
    private NsiaUserMapper nsiaUserMapper;

    @Autowired
    private NsiaMenuMapper nsiaMenuMapper;

    @Override
    public List<NsiaMenu> getMenusByUserId(Long userId) {
        if(!Objects.isNull(userId) && userId > 0) {
            NsiaUser nsiaUser = nsiaUserMapper.selectById(userId);
            if(!Objects.isNull(nsiaUser)) {
                List<NsiaUserMenu> nsiaUserMenus = nsiaUserMenuMapper.selectList(new QueryWrapper<NsiaUserMenu>().eq("user_id", userId));
                if(!CollectionUtil.isEmpty(nsiaUserMenus)) {
                    return nsiaMenuMapper.selectList(new QueryWrapper<NsiaMenu>().in("id", nsiaUserMenus.stream().map(NsiaUserMenu::getMenuId).collect(Collectors.toSet())));
                }
            } else {
                deleteMenusByUserId(userId);
            }
        }
        return null;
    }

    @Override
    public void deleteMenusByUserId(Long userId) {
        if(!Objects.isNull(userId)) {
            nsiaUserMenuMapper.delete(new QueryWrapper<NsiaUserMenu>().eq("user_id", userId));
        }
    }

    @Override
    public void addMenusByUserId(List<Integer> menuIds, Long userId) {
        if(!Objects.isNull(userId) && userId > 0) {
            NsiaUser nsiaUser = nsiaUserMapper.selectById(userId);
            if(!Objects.isNull(nsiaUser)) {
                if(Objects.isNull(menuIds)) {
                    List<NsiaMenu> menus = nsiaMenuMapper.selectList(new QueryWrapper<NsiaMenu>().eq("level", 2));
                    menuIds = menus.stream().map(NsiaMenu::getId).collect(Collectors.toList());
                }
                for(Integer menuId : menuIds) {
                    NsiaUserMenu nsiaUserMenu = new NsiaUserMenu();
                    nsiaUserMenu.setMenuId(menuId);
                    nsiaUserMenu.setUserId(userId);
                    nsiaUserMenuMapper.insert(nsiaUserMenu);
                }
            }
        }
    }
}
